var app = angular.module ( 'formCustSqlViewApp' );
// search-page
app.directive ( 'searchPage' , [ '$timeout' , '$injector' , 'searchService' , 'baseService', function ( $timeout , $injector , searchService , baseService) {

	return {
	    restrict : 'E' ,
	    scope : {
	        searchScope : "=" ,
	        parent : "=" ,
	        noAdd : "=" ,
	        pName : "="
	    } ,
	    priority : 100 ,
	    templateUrl : "../../../form/formCustSql/view/searchPage.html" ,
	    replace : true ,
	    link : function ( scope , elm , attrs ) {

		    scope.service = searchService;
		    scope.base = baseService;
		    scope.formCustSqlViewService = $injector.get ( "formCustSqlViewService" );
		    scope.conditions = [ ];
		    
		    // 跳转到设计页面
		    scope.design = function ( ) {

			    var url = "../formCustSqlEdit.html?id="+scope.parent.vo.id+"&operType=edit";
			    window.open ( url );
		    };

		    // 监听回车键
		    scope.doSearch = function ( e ) {

			    var keycode = window.event ? e.keyCode : e.which;
			    if ( keycode == 13 ) {
				    scope.searchFn ( );
			    }
		    };

		    /*** 查询*/
		    scope.searchFn = function (  ) {
			    scope.parent.pageParams.params = scope.getParams ( );
			    // 刷新功能
			    scope.reloadPageData ( scope.parent.listScope.pageScope );
		    };
		    
		    window.reloadGrid = scope.searchFn;
		    
		    // 重置
		    scope.resetFn = function ( ) {

		    	var conditions = [];
			    for ( var i = 0 ; i < scope.oldConditions.length ; i++ ) {
			    	var cond = angular.copy ( scope.oldConditions[i] );
			    	conditions.push(cond);
		    		// 处理单复选框的数据字典
			    	if([7,9].indexOf(cond.ctltype)>=0){
			    		cond.json = scope.conditions[i].json;
			    	}
			    }
			    scope.conditions = conditions;

			    if(scope.parent.sortFields){
			    	 // 去掉排序
				    for ( var i = 0 ; i < scope.parent.sortFields.length ; i++ ) {
					    var field = scope.parent.sortFields[i];
					    field.sortDir = null;
					    scope.previewService.setDefaultSort ( scope.parent , field );
				    }
			    }
			   

		    };

		    // 刷新
		    scope.reloadPageData = function ( tempScope ) {

			    tempScope.$broadcast ( 'setPageScope' , {
				    loadByBro : true
			    } );
			    tempScope.$broadcast ( 'pageDataChange' , {} );
			    tempScope.$on ( "pageDataLoaded" , function ( ) {

				    tempScope.$broadcast ( 'setPageScope' , {
					    loadByBro : false
				    } );
			    } );
		    } ;
		    

		    // 获取查询参数
		    scope.getParams = function ( ) {

			    var searchParam = new Array ( );
			    if ( scope.conditions ) {
				    for ( var i = 0 ; i < scope.conditions.length ; i++ ) {
					    var c = scope.conditions[i];

					    // 判断原有的条件中是否有值,如果有,并且不是isInit的时候,那么当此时的值为空,则需要传到后台,否则就会一直沿用原来的值,不会查询空的值
					    if ( !window.isStrNull ( c.v ) || !window.isStrNull ( c.val ) || ( c.oldCond && c.oldCond.v && !c.oldCond.isInit ) ) {
						    var val = c.v || c.val;
						    if ( c.json == "yyyy-MM-dd" ) {
							    if ( c.cntype == ">=" || c.cntype == ">" ) {
								    val = val + " 00:00:00";
							    } else if ( c.cntype == "<=" || c.cntype == "<" ) {
								    val = val + " 23:59:59";
							    }
						    }
						    searchParam.push ( {
						        name : c.name ,
						        con : c.cntype ,
						        val : val ,
						        bracket : c.bracket ,
						        andOr : c.andOr ,
						        isGroup : c.isGroup
						    } );
					    }
				    }
			    }
			    var oldParam = scope.parent.pageParams.params || {};
			    oldParam = JsonUtil.ps ( oldParam );
			    if ( oldParam && oldParam.queryData ) {
				    for ( var i = 0 ; i < oldParam.queryData.length ; i++ ) {
					    if ( oldParam.queryData[i].isInit ) {
						    searchParam.push ( oldParam.queryData[i] );
					    }
				    }
			    }
			    var newParam = "";
			    if ( searchParam.length > 0 ) {
				    newParam = $.extend ( oldParam , {} );
				    newParam.queryData = searchParam;
				    newParam.orderBy = oldParam.orderBy;
				    newParam = JSON.stringify ( newParam );
			    } else if ( oldParam ) {
				    var tempParam = {};
				    for ( var key in oldParam ) {
					    if ( key != "queryData" ) {
						    tempParam[key] = oldParam[key];
					    }
				    }
				    // 保留原始的排序规则
				    newParam = JSON.stringify ( tempParam );

			    }
			    return newParam;
		    }

		    // 获取查询sql 调试sql
		    scope.getSearchSql = function ( ) {

			    // 注意 ： 需要点击查询之后才会更新 scope.parent.pageParams.params
			    baseService.post ( scope.parent.vo.sqlUrl , {
				    params : scope.getParams ( )
			    } ).then(function ( data ) {
				    console.info ( data )
				    $.Dialog.success ( "请打开f12查看network或者console控制台" );
			    });
		    };

		    // 更改自定义查询的控件类型
		    scope.changeCtlType = function ( ) {

			    switch ( scope.search.ctltype ) {
				    case 15 :
				    break;
			    }
		    }
		    // 添加自定义的字段查询
		    scope.addSearchField = function ( ) {

			    var search = scope.search;
			    if ( !search || !search.name ) {
				    alert ( "请选择字段" );
				    return;
			    }
			    if ( !search.cntype ) {
				    alert ( "请选择条件类型" );
				    return;
			    }
			    if ( !search.ctltype ) {
				    alert ( "请选择控件类型" );
				    return;
			    }
			    var list = scope.parent.fields;
			    // 获取desc
			    for ( var i = 0 ; i < list.length ; i++ ) {
				    if ( list[i].fieldName == search.name ) {
					    search.desc = list[i].fieldDesc;
					    search.type = list[i].dataType;
					    break;
				    }
			    }
			    scope.conditions.push ( {
			        cntype : search.cntype ,
			        ctltype : search.ctltype ,
			        init : false ,
			        desc : search.desc ,
			        name : search.name ,
			        json : JsonUtil.ps ( search.json ) ,
			        sn : scope.conditions.length + 1 ,
			        type : search.type ,
			    } );

			    // 判断是否有范围条件处理
			    fn ( );
		    };

		    scope.switchSearch = function ( ) {

			    scope.hideSearch = !scope.hideSearch;
			    scope.parent.listService.setListPageHeight ( scope.parent );
		    }
		    
		    $(window).resize(function() {
		    	 scope.parent.listService.setListPageHeight ( scope.parent );
		    })
		    
		    scope.focus = function(left,right){
		    	left.wcls = "wd180 fs14";
		    	left.focus = true;
		    	if(right){
		    		right.focus = true;
		    		right.wcls='wd50 fs12';
		    	}
		    }
		    
		    scope.blur = function(left){
		    	left.focus = false;
		    	if(left.hasBetween){
		    		left.wcls='wd100 fs12'
		    		left.betweenCondition.focus = false;
		    		left.betweenCondition.wcls='wd100 fs12'
		    	}
		    }


		    scope.initSearchCond = function ( ) {

			    // 获取可排序的字段列表
			    scope.conditions = scope.parent ? scope.parent.conditions : [ ];
			    var tempCondList = [ ];
			    for ( var i = 0 ; i < scope.conditions.length ; i++ ) {
				    var cond = scope.conditions[i];
				    cond.wcls = "wd180";
				    var cnType = cond.cntype;
				    cond.json = JsonUtil.ps(cond.json) || cond.json;
				    if(cond.ctltype==2){
				    	cond.ctltype = 1;
				    }
				    if ( cnType.indexOf ( "," ) > 0 ) {
					    cnType = cnType.split ( "," );
					    cond.cntype = cnType[0];
					    cond.wcls = "wd90 fs12";

					    var tempCond = angular.copy ( cond );
					    tempCond.cntype = cnType[1];
					    tempCond.hidden = true;// hidden表示
					    // 当前这个condition条件,是另一个condition的between集
					    cond.betweenCondition = tempCond;
					    cond.hasBetween = true;
					    tempCondList.push ( tempCond );
				    }
				    cond.oldCond = angular.copy ( cond );
				    cond.showType = cond.showType + "";
				    switch ( cond.showType ) {
					    default :
					    case "1" :// 显示
					    break;
					    case "2" :// 隐藏
					    case "4" :// 移除 [移除的不会从后台传过来,一般在系统默认的查询条件下才使用]
						    cond.hidden = true;
					    break;
					    case "3" :// 禁用
						    cond.disabled = true;
				    }

				    // 设置显示多少列
				    cond.width = 300 * ( cond.colMuti || 1 ); // 默认每行显示四列
				    if ( cond.colMuti == 4 ) {
					    cond.width = "100%";
				    }
				    cond.colCls = "";
				    if ( cond.newLine == 1 ) {
					    cond.colCls += " c-l";
				    }
				    
				    // 设置默认值
				    var dfDataType = cond.dfDataType + "";
				    if(!cond.v){
				    	 switch(dfDataType){
				    		 case "1" :
				    			 // 固定值 无需处理
				    			 break
				    		 case "2" :
				    			 // 当前时间
				    			 cond.v = new Date().format(cond.json||"yyyy-MM-dd hh:mm:ss");
				    			 break
				    		 case "3" :
				    			 // 当前用户ID
				    			 // 不知道前端怎么获取,不过也没关系 一般用不到, 因为这个默认值一般用在后台进行赋值
				    			 break
				    		 case "4" :
				    			 // 当前用户名称
				    			 // 不知道前端怎么获取,不过也没关系 一般用不到, 因为这个默认值一般用在后台进行赋值
				    			 break
				    		 case "7" :
				    			 // 当前组织ID
				    			 // 不知道前端怎么获取,不过也没关系 一般用不到, 因为这个默认值一般用在后台进行赋值
				    			 break
				    		 case "8" :
				    			 // 当前组织名称
				    			 // 不知道前端怎么获取,不过也没关系 一般用不到, 因为这个默认值一般用在后台进行赋值
				    			 break
						 }
				    }
				   

				    // 初始化URL中的参数
				    if ( typeof ( initParam ) != "undefined" && initParam[cond.name] ) {
					    cond.v = initParam[cond.name];
				    }

			    }
			    scope.conditions.pushAll ( tempCondList );

			    scope.oldConditions = angular.copy ( scope.conditions );

			    var expand = scope.parent.expand;
			    if ( expand && expand.sort && expand.sort.sortAble == 1 ) {
				    scope.sortAble = true;
			    }
			    var params = scope.getParams();
			    
			    scope.parent.pageParams = {params:params};

			    scope.parent.searchService = searchService;
			    
			    window.setTimeout(function(){
			    	$.handlerCollapseExpand();
			    },1000)
		    }
		    
		    scope.formCustSqlViewService.bindParent ( scope , 'search' , scope.pName , scope.initSearchCond );

	    }
	};
} ] );

app.service ( 'searchService' , [ '$injector' , function ( $injector ) {

	var service = {
		closeModal : function ( scope ) {
			// var curModal = $ ( "#" + scope.__searchId );
			var modalName = scope.parent.modalName;
			$ ( "#" + modalName ).hide ( );
			$ ( "#" + modalName ).siblings ( ".searchPage , .listPage" ).show ( );
		}
	};
	return service;
} ] );
// 可格式化
